package org.dawfinn.droiditarian.server.webview;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;

import org.dawfinn.droiditarian.DeedLocationQuery;
import org.dawfinn.droiditarian.client.webview.ClientDeedLocation;
import org.dawfinn.droiditarian.client.webview.DeedLocationQueryParams;
import org.dawfinn.droiditarian.client.webview.DeedLocationQueryService;
import org.dawfinn.droiditarian.server.Geohash;
import org.dawfinn.droiditarian.server.data.DeedLocation;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class DeedLocationQueryServiceImpl extends RemoteServiceServlet
		implements DeedLocationQueryService {

	private final DateFormat dateFormat = DateFormat.getDateTimeInstance();

	public ClientDeedLocation[] getDeedLocations(DeedLocationQueryParams params) {
		List<DeedLocation> deeds = DeedLocationQuery.getDeedLocations(params
				.getSize());

		if (deeds == null || deeds.size() == 0)
			return new ClientDeedLocation[0];

		List<ClientDeedLocation> clientDeeds = new ArrayList<ClientDeedLocation>();

		for (DeedLocation dl : deeds) {
			ClientDeedLocation clientDeed = null;

			double[] loc = Geohash.getInstance().decode(dl.getGeohash());
			double latitude = loc[0];
			double longitude = loc[1];

			String localityString = buildLocalityString(dl);

			String websafeKey = KeyFactory.keyToString(dl.getKey());
			String completionDate = dateFormat.format(dl.getCompletedDate());

			clientDeed = new ClientDeedLocation(websafeKey, latitude, longitude,
					dl.getDeedTitle(), completionDate, localityString,
					dl.getImage() != null);

			clientDeeds.add(clientDeed);
		}

		return clientDeeds.toArray(new ClientDeedLocation[params.getSize()]);
	}

	private String buildLocalityString(DeedLocation dl) {
		String locality = dl.getLocality();
		String adminArea = dl.getAdminArea();
		String country = dl.getCountry();

		String localityString = "";

		if (country != null) {
			if (locality == null)
				if (adminArea == null)
					localityString = country;
				else
					localityString = adminArea + ", " + country;
			else if (adminArea == null)
				localityString = locality + ", " + country;
			else
				localityString = locality + ", " + adminArea + ", " + country;
		}

		return localityString;
	}
}
